package com.plusjun.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.plusjun.common.to.es.SkuEsModel;
import com.plusjun.common.utils.R;
import com.plusjun.search.config.ESConfig;
import com.plusjun.search.constant.ESConstant;
import com.plusjun.search.feign.ProductFeignService;
import com.plusjun.search.service.MallSearchService;
import com.plusjun.search.vo.AttrResponseVO;
import com.plusjun.search.vo.BrandVO;
import com.plusjun.search.vo.SearchParamVO;
import com.plusjun.search.vo.SearchResultVO;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Resource
    private RestHighLevelClient client;

    @Resource
    private ProductFeignService productFeignService;

    // 去ES进行检索
    @Override
    public SearchResultVO search(SearchParamVO param) {
        // 1、动态构建出查询需要的DSL语句
        SearchResultVO result = null;

        // 1)、准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);
        // 2)、执行检索请求,达到响应数据
        try {
            SearchResponse response = client.search(searchRequest, ESConfig.COMMON_OPTIONS);
            // 3)、分析响应数据，封装成我们需要的格式
            result = buildSearchResult(response, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 构建查询请求
     * #模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存），排序，分页，高亮，聚合分析
     *
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParamVO param) {
        // 构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /**
         * 模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存）
         */
        // 1、构建boolQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        sourceBuilder.query(boolQuery);
        // 1.1、模糊匹配
        if (StringUtils.isNotEmpty(param.getKeyWord())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyWord()));
        }
        // 1.2、bool-Filter
        // 1.2.1、按照三级分类id查询
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        // 1.2.2、按照品牌id查询
        if (param.getBrandId() != null) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        // 1.2.3、按照所有指定的属性进行查询
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                // 每一个都必须生产一个nested查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }

        // 1.2.4、按照是否有库存查询
        if (param.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        // 1.2.5、按照价格区间查询
        if (StringUtils.isNotEmpty(param.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String skuPrice = param.getSkuPrice();
            String[] s = skuPrice.split("_");
            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(s[0]);
                }
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        // 把之前所有条件都拿来进行封装
        sourceBuilder.query(boolQuery);
        /**
         * 2、排序，分页，高亮
         */
        // 2.1、排序
        if (StringUtils.isNotEmpty(param.getSort())) {
            String sort = param.getSort();
            String[] s = sort.split("_");
            String sortName = s[0];
            SortOrder sortType = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(sortName, sortType);
        }
        // 2.2、分页 默认从第一页开始，每页5个
        sourceBuilder.from((param.getPageNum() - 1) * ESConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(ESConstant.PRODUCT_PAGESIZE);
        // 2.3、高亮
        if (StringUtils.isNotEmpty(param.getKeyWord())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }
        /**
         * 聚合分析
         */

        // 3.1、品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        // 3.1.1、品牌聚合的子组合--品牌名
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName")).size(100);
        // 3.1.2、品牌聚合的子组合--品牌图片
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg")).size(100);
        // 聚合品牌
        sourceBuilder.aggregation(brand_agg);

        // 3.2、分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId");
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName")).size(1);
        // 聚合分类
        sourceBuilder.aggregation(catalog_agg);

        // 3.3、属性聚合(嵌入式聚合）
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        // 3.3.1、属性聚合中的子聚合--attr_id_agg(聚合出当前所有的attrId)
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attr_agg.subAggregation(attr_id_agg);
        // 3.3.1.1、属性聚合中的属性id聚合中的子聚合--attr_name_agg(聚合出当前attr_id对应的名字）
        TermsAggregationBuilder attr_name_agg = AggregationBuilders.terms("attr_name_agg").field("attrs.attrName");
        attr_id_agg.subAggregation(attr_name_agg);
        // 3.3.1.2、属性聚合中的属性id聚合中的子聚合--attr_value_agg(聚合出当前attr_id对应的所有可能值）
        TermsAggregationBuilder attr_value_agg = AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue");
        attr_id_agg.subAggregation(attr_value_agg);
        // 聚合属性
        sourceBuilder.aggregation(attr_agg);
        SearchRequest searchRequest = new SearchRequest(new String[]{ESConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }

    /**
     * 构建返回结果
     *
     * @param response
     * @param param
     * @return
     */
    private SearchResultVO buildSearchResult(SearchResponse response, SearchParamVO param) {
        SearchResultVO result = new SearchResultVO();
        SearchHits hits = response.getHits();
        /**************分析聚合信息**************/
        // 1、返回所有查询到的商品
        List<SkuEsModel> esModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (StringUtils.isNotEmpty(param.getKeyWord())) {
                    // 高亮
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }
                esModels.add(skuEsModel);
            }
        }
        result.setProducts(esModels);
        // 2、当前商品所涉及的所有属性
        List<SearchResultVO.AttrVO> attrVOs = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        // 得到attr_id_agg
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResultVO.AttrVO attrVO = new SearchResultVO.AttrVO();
            // 得到attrId
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVO.setAttrId(attrId);
            // 得到attrName
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            attrVO.setAttrName(attrName);
            // 得到attrValues
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                return ((Terms.Bucket) item).getKeyAsString();
            }).collect(Collectors.toList());
            attrVO.setAttrValue(attrValues);
            attrVOs.add(attrVO);
        }

        result.setAttrs(attrVOs);
        // 3、当前商品所涉及的所有品牌信息
        List<SearchResultVO.BrandVO> brandVOS = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResultVO.BrandVO brandVO = new SearchResultVO.BrandVO();
            // 得到品牌的id
            long brandId = bucket.getKeyAsNumber().longValue();
            brandVO.setBrandId(brandId);
            // 得到品牌的名字
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVO.setBrandName(brandName);
            // 得到品牌的图片
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVO.setBrandImg(brandImg);

            brandVOS.add(brandVO);
        }
        result.setBrands(brandVOS);
        // 4、当前商品所涉及的所有分类信息
        // 4.1、获取到catalog_agg聚合
        // 用于接收CatalogVO
        List<SearchResultVO.CatalogVO> catalogVOS = new ArrayList<>();
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        // 4.2、从catalog_agg中获取到buckets（buckets中是我们需要的信息）
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        if (buckets != null && buckets.size() > 0) {
            for (Terms.Bucket bucket : buckets) {
                SearchResultVO.CatalogVO catalogVO = new SearchResultVO.CatalogVO();
                // 提取出分类id
                String keyAsString = bucket.getKeyAsString();
                catalogVO.setCatalogId(Long.parseLong(keyAsString));

                // 得到分类名--子聚合
                ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
                String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
                catalogVO.setCatalogName(catalog_name);

                catalogVOS.add(catalogVO);
            }
        }
        result.setCatalogs(catalogVOS);
        // 5、当前商品所涉及的所有分页信息
        /*******************************/
        // 5.1、当前页码
        Integer pageNum = param.getPageNum();
        result.setPageNum(pageNum);
        // 5.2、总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        // 5.3、总页码
        int totalPages = (int) (total % ESConstant.PRODUCT_PAGESIZE == 0 ? (total / ESConstant.PRODUCT_PAGESIZE) : (total / ESConstant.PRODUCT_PAGESIZE + 1));
        result.setTotalPages(totalPages);
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i < totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        // 6、构建面包屑导航功能
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResultVO.NavVo> navVoList = param.getAttrs().stream().map(attr -> {
                SearchResultVO.NavVo navVo = new SearchResultVO.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                // 远程调用product服务，找到对应的attrName
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                result.getAttrIds().add(Long.parseLong(s[0]));

                if (r.getCode() == 0) {
                    AttrResponseVO data = (AttrResponseVO) r.getData("attr", new TypeReference<AttrResponseVO>() {
                    });
                    navVo.setNavName(data.getAttrName());
                } else {
                    // 调用失败
                    navVo.setNavName(s[0]);
                }
                // 取消面包屑导航之后，要跳转到哪
                // 拿到所有查询条件，去掉当前
                // 进行中文编码
                String replace = replaceQueryString(param, attr, "attrs");
                navVo.setLink(ESConstant.LIST_URL + replace);
                System.out.println(navVo.getLink());
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navVoList);
        }

        // 品牌、分类
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            List<SearchResultVO.NavVo> navs = result.getNavs();
            SearchResultVO.NavVo navVo = new SearchResultVO.NavVo();
            navVo.setNavName("品牌");
            // 远程调用
            R r = productFeignService.brandsInfo(param.getBrandId());
            if(r.getCode() == 0) {
                List<BrandVO> brands = (List<BrandVO>) r.getData("brands", new TypeReference<List<BrandVO>>() {
                });
                StringBuilder stringBuilder = new StringBuilder();
                String replace = "";
                for (BrandVO brand : brands) {
                    stringBuilder.append(brand.getBrandName() + ";");
                    replace = replaceQueryString(param,brand.getBrandId()+"","brandId");
                }
                navVo.setNavValue(stringBuilder.toString());
                navVo.setLink(ESConstant.LIST_URL + replace);
            }
            navs.add(navVo);
        }

        // TODO 分类
            return result;
    }

    private String replaceQueryString(SearchParamVO param, String value, String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            encode = encode.replace("+", "%20"); //浏览器对空格的编码和java不一样
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return param.get_queryString().replace("&" + key + "=" + encode, "");
    }
}
